<script setup lang="ts">
import { ref, reactive, watch, PropType, toRef, nextTick } from "vue";
import type { FormRules } from "element-plus";

const props = defineProps({
  formInline: {
    type: Object,
    default: () => ({})
  },
  categoryTreeData: {
    type: Array as PropType<any[]>,
    default: () => []
  }
});

const ruleFormRef = ref();
const newFormInline = reactive({ ...props.formInline });
const categoryTree = toRef(props, "categoryTreeData");

watch(
  () => props.formInline,
  newVal => {
    Object.assign(newFormInline, newVal);

    // 当表单数据重置时，同时清除表单验证状态
    if (ruleFormRef.value && Object.keys(newVal).length > 0) {
      // 使用 nextTick 确保 DOM 更新后再清除验证状态
      nextTick(() => {
        ruleFormRef.value?.clearValidate();
      });
    }
  },
  { deep: true, immediate: true }
);

const formRules = reactive<FormRules>({
  name: [{ required: true, message: "请输入分类名称", trigger: "blur" }]
});

const emits = defineEmits(["submit"]);

function getRef() {
  return ruleFormRef.value;
}

const submitForm = async () => {
  const formEl = ruleFormRef.value;
  if (!formEl) return;
  await formEl.validate(valid => {
    if (valid) {
      emits("submit", newFormInline);
    }
  });
};

defineExpose({ getRef, submitForm });
</script>

<template>
  <el-form ref="ruleFormRef" :model="newFormInline" :rules="formRules" label-width="80px">
    <el-form-item label="分类名称" prop="name">
      <el-input v-model="newFormInline.name" clearable placeholder="请输入分类名称" />
    </el-form-item>
    <el-form-item label="上级分类" prop="parent_id">
      <el-tree-select
        v-model="newFormInline.parent_id"
        :data="categoryTree"
        :props="{ label: 'name', value: 'id' }"
        check-strictly
        node-key="id"
        clearable
        placeholder="请选择上级分类"
        class="w-full"
      />
    </el-form-item>
    <el-form-item label="排序" prop="sort_order">
      <el-input-number v-model="newFormInline.sort_order" :min="0" controls-position="right" />
    </el-form-item>
    <el-form-item label="分类图标" prop="icon">
      <el-input v-model="newFormInline.icon" clearable placeholder="请输入分类图标" />
    </el-form-item>
    <el-form-item label="是否显示" prop="is_displayed">
      <el-switch
        v-model="newFormInline.is_displayed"
        :active-value="1"
        :inactive-value="0"
        inline-prompt
        active-text="是"
        inactive-text="否"
      />
    </el-form-item>
  </el-form>
</template>
